from logging import getLogger

from twisted.web.resource import Resource

from zope.component import getGlobalSiteManager

from meercat.storage.interfaces import IStorage

from meercat.server.rest import getRestResource



log = getLogger('meercat.server.nevow.rest')

registry = getGlobalSiteManager()

class RestGenerator(Resource):
    children = {}
    
    def __init__(self, format='web', *args, **kwargs):
        log.info('%s.__init__(format=%s, *%s, **%s)' % (str(self), str(format), 
                                                        str(args), str(kwargs)))
        self.format = format
    
    def listDynamicNames(self):
        log.info('%s.listDynamicNames()' % (str(self),))
        return list(map(lambda x: x[0], registry.getUtilitiesFor(IStorage)))
    
    def listDynamicEntities(self, request=None):
        log.info('%s.listDynamicEntities(request=%s)' % (str(self),str(request),))
        return list(map(lambda x: self.getChild(x, request),
                        self.listDynamicNames()))
    
    def getChild(self, path, request):
        log.info('%s.listDynamicNames(path=%s,request=%s)' % (str(self),str(path), str(request)))
        return getRestResource(registry.getUtility(IStorage, path),self.format)
    
    def render_GET(self, request):
        links = '\n'.join(map(lambda n: '<li><a href="%s/%s">%s</a></li>' % (request.path, n, n),
                              self.listNames()))
        
        return str('''
            <html>
            <head><title>REST Sources</title></head>
            <body>
            <ul>
            %s
            </ul>
            </body>
            </html>''' % (links,))

